/**   
 *    
 * 项目名称：a_yongan   
 * 类名称：ProcessProcessServiceImpl   
 * 类描述：   
 * 创建人：liubo   
 * 创建时间：2018年6月18日 下午2:10:43    
 * 修改时间：2018年6月18日 下午2:10:43   
 * 修改备注：   
 * @version    
 *    
 */
package com.yongan.production.service.impl;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.production.dao.ProcessProcessDao;
import com.yongan.production.entity.ProcessDetails;
import com.yongan.production.entity.ProcessProcess;
import com.yongan.production.service.ProcessDetailsService;
import com.yongan.production.service.ProcessProcessService;
import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.warehouse.dao.GoodsinformationDao;
import com.yongan.warehouse.entity.Goodsinformation;
import com.yongan.warehouse.service.GoodsinformationService;
import com.yongan.workflow.service.PersonalWorkService;

/**
 * @author liubo
 * 
 */
@Service
public class ProcessProcessServiceImpl implements ProcessProcessService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ProcessProcessDao processProcessDao;
	@Autowired
	private ProcessDetailsService processDetailsService;
	@Autowired
	private GoodsinformationService goodsinformationService;
	@Autowired
	private GoodsinformationDao goodsinformationDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";
	@Autowired
	private PersonalWorkService personalWorkService;
	@Override
	public List<ProcessProcess> getProcessProcess(int offset, int limit,String type) {
		List<ProcessProcess> list = processProcessDao.queryAll(offset, limit,type);
		/*
		 * for(ProcessProcess pp:list){ String id = pp.getProcessProcessId();
		 * Goodsinformation gi =
		 * goodsinformationService.getGoodsinformationById(id);
		 * pp.setGoodsinformation(gi); }
		 */
		return list;
	}

	@Override
	public ProcessProcess getProcessProcessById(String processProcessId) {
		ProcessProcess processProcess = processProcessDao
				.queryById(processProcessId);
		processProcess.setDetails(processDetailsService
				.getProcessDetailsList(processProcessId));
		return processProcess;
	}

	@Transactional
	@Override
	public Execution executeProcessProcess(ProcessProcess processProcess,
			String processProcessId, String md5,String isflowwork,String userid,String flowtype) throws UserException {
		if (md5 == null || !md5.equals(getMD5(processProcessId))) {
			// throw new UserException("user data rewrite");
		}
		
		if(flowtype.equals("阀体类")){
			flowtype = "ftl";
		}else if(flowtype.equals("阀座类")){
			flowtype = "fzl";
		}else if(flowtype.equals("阀杆类")){
			flowtype = "fganl";
		}else if(flowtype.equals("阀盖类")){
			flowtype = "fgl";
		}
		try {
			if (processProcess == null) {
				ProcessProcess pp = processProcessDao.queryById(processProcessId);
				if(pp.getProcessProcessIsrk().equals("true")){
					List<ProcessDetails> detailsall = processDetailsService.getProcessDetailsList(processProcessId);
					ProcessDetails detail = detailsall.get(detailsall.size() - 1);
					int reduceCount = reduceNumber(detail, "reduce");
					if (reduceCount <= 0) {
						throw new UserException("delete failed");
					}
				}else if(pp.getProcessProcessIsll().equals("true")){
					List<ProcessDetails> detailsall = processDetailsService.getProcessDetailsList(processProcessId);
					ProcessDetails detail = detailsall.get(0);
					int reduceCount = reduceNumber(detail, "add");
					if (reduceCount <= 0) {
						throw new UserException("delete failed");
					}
				}
				Boolean pws = false;
				pws = personalWorkService.deletePersonalWork(processProcessId);
				int deleteCount = processProcessDao
						.deleteProcessProcess(processProcessId);
				int deleteDetails = processDetailsService
						.deleteAllByTopId(processProcessId);
				if (deleteCount <= 0 & deleteDetails <= 0 & !pws) {
					throw new UserException("delete failed");
				} else {
					return new Execution(processProcessId, UserStatEnum.SUCCESS);
				}
			} else if ((processProcessId.equals(""))) {
				String topId = UUID.randomUUID().toString();
				processProcess.setProcessProcessId(topId);
				int addCount = processProcessDao
						.insertProcessProcess(processProcess);
				List<ProcessDetails> details = processProcess.getDetails();
				Boolean isDetails = false;
				for (ProcessDetails detail : details) {
					detail.setProcessDetailsId(UUID.randomUUID().toString());
					detail.setTopId(topId);
					int detailAdd = processDetailsService
							.addProcessDetails(detail);
					if (detailAdd <= 0) {
						isDetails = true;
					}
				}
				Boolean pws = false;
				if(isflowwork.equals("tj")){
					pws = personalWorkService.addPersonalWork("processprocess", userid, topId,flowtype);
					pws = personalWorkService.nextPersonalWork(topId,flowtype);
				}else if(isflowwork.equals("")){
					pws = personalWorkService.addPersonalWork("processprocess", userid, topId,flowtype);
				}else if(isflowwork.equals("ll")){
					pws = personalWorkService.addPersonalWork("processprocess", userid, topId,flowtype);
					this.executeLingLiao(topId, details, "12");
				}
				if (addCount <= 0 & isDetails & !pws) {
					throw new UserException("add failed");
				} else {
					return new Execution(processProcess.getProcessProcessId(),
							UserStatEnum.SUCCESS);
				}
			} else if (!(processProcessId.equals(""))) {
				int updateCount = processProcessDao
						.updateProcessProcess(processProcess);
				List<ProcessDetails> details = processProcess.getDetails();
				//System.out.println("==="+details);
				Boolean isDetails = false;
				for (ProcessDetails detail : details) {
					int detailsCount = processDetailsService
							.updateProcessDetails(detail);
					if (detailsCount <= 0) {
						isDetails = true;
					}
				}
				Boolean pws = false;
				if(isflowwork.equals("tj")){
					pws = personalWorkService.nextPersonalWork(processProcessId,flowtype);
				}else if(isflowwork.equals("th")){
					pws = personalWorkService.upPersonalWork(processProcessId,flowtype);
				}else if(isflowwork.equals("rk")){
					ProcessProcess pp = processProcessDao.queryById(processProcessId);
					if(pp.getProcessProcessIsrk().equals("false")){
						this.executeRuku(processProcessId, details, "1221");
					}else{
						return new Execution(processProcessId, UserStatEnum.FAILED);
					}
				}
				if (updateCount <= 0 & isDetails & !pws) {
					throw new UserException("update failed");
				} else {
					return new Execution(processProcessId, UserStatEnum.SUCCESS);
				}
			} else {
				throw new UserException("parameter error");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}

	public int getCount(String type) {
		return processProcessDao.queryCount(type);
	}

	private String getMD5(String Id) {
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

	@Transactional
	@Override
	public Execution executeRuku(String processProcessId,
			List<ProcessDetails> detailsall, String md5) throws UserException {
		// ProcessProcess pp = processProcessDao.queryById(processProcessId);
		ProcessDetails detail = detailsall.get(detailsall.size() - 1);
		try {
			Boolean is = false;
			int jie = reduceNumber(detail, "add");
			if (jie <= 0) {
				is = true;
			}
			int zhu = processProcessDao.updateRuku("true", processProcessId);
			if (!is & zhu <= 0) {
				throw new UserException("ruku failed");
			} else {
				return new Execution("", UserStatEnum.SUCCESS);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}
	@Transactional
	@Override
	public Execution executeLingLiao(String processProcessId,
			List<ProcessDetails> detailsall, String md5) throws UserException {
		// ProcessProcess pp = processProcessDao.queryById(processProcessId);
		ProcessDetails detail = detailsall.get(0);
		try {
			Boolean is = false;
			int jie = reduceNumberLl(detail, "reduce");
			if (jie <= 0) {
				is = true;
			}
			int zhu = processProcessDao.updateLingLiao("true", processProcessId);
			if (!is & zhu <= 0) {
				throw new UserException("ruku failed");
			} else {
				return new Execution("", UserStatEnum.SUCCESS);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}
	public int reduceNumber(ProcessDetails igd, String type) {
		// Integer zonghe =
		// (Integer.parseInt(shuliang))*(Integer.parseInt(igd.getDetailsSl()));
		// System.out.println(shuliang+"========"+String.valueOf(zonghe));
		Goodsinformation gi = goodsinformationDao.queryById(igd
				.getProcessDetailsLjmcId());
		return goodsinformationDao.reduceNumber(gi.getGoodsinformationNumber(),
				type, Integer.parseInt(igd.getProcessDetailsWcsl()),
				Integer.parseInt(igd.getProcessDetailsWcsl()));
	}
	public int reduceNumberLl(ProcessDetails igd, String type) {
		// Integer zonghe =
		// (Integer.parseInt(shuliang))*(Integer.parseInt(igd.getDetailsSl()));
		// System.out.println(shuliang+"========"+String.valueOf(zonghe));
		Goodsinformation gi = goodsinformationDao.queryById(igd
				.getProcessDetailsLjmcId());
		return goodsinformationDao.reduceNumber(gi.getGoodsinformationNumber(),
				type, Integer.parseInt(igd.getProcessDetailsRwsl()),
				Integer.parseInt(igd.getProcessDetailsRwsl()));
	}
}
